import { defineStore } from "pinia";
import { ref } from "vue";
import {
  userLogin, //登陆
  getUserInfo, //获取用户信息
  listGodown, //获取仓库列表
  updatePassword, //修改密码
  updateUserInfo, //修改用户信息
} from "../../utils/api/user/userApi";
let menu = [
  "home",
  "InventoryManagement",
  "ApprovalManagement",
  "LossReportedManagement",
  "LossReportingApproval",
  "Materialview",
];
const workbenchList: Array<any> = [
  {
    naem: "新建入库",
    img: "home-warehousing.png",
    id: "IMput",
    color: "#9CE4C9",
    theme: "InventoryManagement",
    path: "/pages/InventoryManagement/IMput/addIMput/addIMput",
  },
  {
    naem: "入库审核",
    img: "home-warehousing-a.png",
    id: "APput",
    color: "#A5BDF9",
    theme: "ApprovalManagement",
    path: "/pages/ApprovalManagement/APput/APput",
  },
  {
    naem: "新增出库",
    img: "hoime-outbound.png",
    id: "IMout",
    color: "#F9C9A5",
    theme: "InventoryManagement",
    path: "/pages/InventoryManagement/IMout/addIMout/addIMout",
  },
  {
    naem: "出库审核",
    img: "home-storehouse-a.png",
    id: "APout",
    color: "#A5BDF9",
    theme: "ApprovalManagement",
    path: "/pages/ApprovalManagement/APout/APout",
  },
  {
    naem: "新增盘点",
    img: "home-Inventory.png",
    id: "IMcheck",
    color: "#F9C9A5",
    theme: "InventoryManagement",
    path: "/pages/InventoryManagement/IMcheck/addIMcheck/addIMcheck",
  },
  {
    naem: "盘点审核",
    img: "home-Inventory-a.png",
    id: "APcheck",
    color: "#F17775",
    theme: "ApprovalManagement",
    path: "/pages/ApprovalManagement/APcheck/APcheck",
  },
  {
    naem: "新增借调",
    img: "home-secondment.png",
    id: "IMborrow",
    color: "#9CE4C9",
    theme: "InventoryManagement",
    path: "/pages/InventoryManagement/IMput/addIMput/addIMput",
  },
  {
    naem: "借调审核",
    img: "home-secondment-a.png",
    id: "APborrow",
    color: "#F17775",
    theme: "ApprovalManagement",
    path: "/pages/ApprovalManagement/APborrow/APborrow",
  },
  {
    naem: "新增报损",
    img: "home-losses.png",
    id: "lossContent",
    color: "#9CE4C9",
    theme: "LossReportedManagement",
    path: "/pages/LossReportedManagement/LRM/lossContent/lossContent",
  },
  {
    naem: "报损审核",
    img: "home-frmloss-a.png",
    id: "loss_review",
    color: "#F9C9A5",
    theme: "LossReportingApproval",
    path: "/pages/LossReportingApproval/LRapprove/LRapprove",
  },
  {
    naem: "数据统计",
    img: "home-statistics.png",
    id: "statistics",
    color: "#A5BDF9",
    theme: "Materialview",
  },
];
import { useToastStore } from "@/stores/modules/toast";
import { useActivePageStore } from "@/stores/modules/activePage";
import { useWorkbenchStore } from "@/stores/modules/workbench";
// 用户相关 定义 Store
export const useMemberStore = defineStore(
  "member",
  () => {
    const toastStore = useToastStore();
    const activePageStore = useActivePageStore();
    const workbenchStore = useWorkbenchStore();
    /************************ 公共变量 ********************** */
    // 存储基准IP
    let baseIP: any = ref("192.168.110.249:80");
    // 存储用户信息
    let profile = reactive<AnyObject>({});
    // 存储 token
    let token = ref("");
    // 存储用户id
    let user_id = ref("");
    //仓库列表
    let Stashlist: any = [];
    let warehouseList: any = reactive({ Stashlist });
    //默认展示仓库
    let defaultStash: any = ref("");
    const GodownCode = ref("");
    // 菜单列表
    const MenuList: any = [];
    const MenuString: any = reactive({ MenuList });
    /********************** 公共方法 ****************** */
    // 登录
    const login = async (data: AnyObject) => {
      // 调用登录接口
      const res: any = await userLogin(data);
      toastStore.show = true;
      toastStore.type = true;
      toastStore.title = "登录成功";
      // 保存基准IP
      // 保存 token
      token.value = res.token;
      // 保存用户id
      user_id.value = res.user_id;
      // // 获取用户信息
      staffFindInfo({ StaffCode: res.user_id });
      // 获取仓库列表
      getStashlist();
      // 跳转到首页
      goHome();
    };
    // 获取用户信息
    const staffFindInfo = async (data: AnyObject) => {
      const res = await getUserInfo(data);
      // 合并用户信息
      Object.assign(profile, res.data);
      if (res.data.RouteMsg) {
        MenuString.MenuList = [];
        let arr = res.data.RouteMsg.split(",");
        // 将'Materialview'移动到数组末尾
        let index = arr.indexOf("Materialview");
        if (index !== -1) {
          // 删除'Materialview'
          arr.splice(index, 1);
          // 插入'Materialview'到数组的开头
          arr.splice(arr.length, arr.length, "Materialview");
        }
        arr.forEach((item: any) => {
          if (menu.includes(item)) {
            starttabList(item);
            MenuString.MenuList.push({
              label: starttabList(item),
              name: item,
            });
          }
        });
      } else {
        MenuString.MenuList = [];
      }
      let arrList = workbenchList.filter((item: any) => {
        return MenuString.MenuList.find(
          (menu: any) => menu.name === item.theme
        );
      });
      workbenchStore.changeList(arrList);
      console.log("用户信息", profile, "菜单列表", MenuString.MenuList);
    };
    //回到首页
    const goHome = () => {
      // 跳转到首页
      setTimeout(() => {
        uni.reLaunch({
          url: "/pages/index/index",
        });
      }, 1500);
    };
    // 菜单列表配置
    const starttabList = (item: any) => {
      let res = "";
      switch (item) {
        case "home":
          res = "工作台";
          break;
        case "InventoryManagement":
          res = "库存管理";
          break;
        case "LossReportedManagement":
          res = "报损管理";
          break;
        case "LossReportingApproval":
          res = "报损审批";
          break;
        case "ApprovalManagement":
          res = "库存审批";
          break;
        case "Materialview":
          res = "统计";
          break;
      }
      return res;
    };
    // 获取仓库列表
    const getStashlist = async () => {
      const res = await listGodown({ godownKeeper: user_id.value });
      warehouseList.Stashlist = res.data;
      defaultStash.value = warehouseList.Stashlist[0] || {};
      GodownCode.value = defaultStash.value.GodownCode || "";
      console.log("仓库列表", warehouseList.Stashlist);
    };
    //切换仓库
    const changeStash = (stash: any) => {
      defaultStash.value = stash;
      GodownCode.value = stash.GodownCode;
      console.log("切换仓库", defaultStash.value);
    };
    // 修改密码
    const updatePasswordFn = async (data: AnyObject) => {
      const res = await updatePassword({
        ...data,
        StaffCode: user_id.value,
      });
      setTimeout(() => {
        exitLogin();
      }, 1500);
      return res;
    };
    // 修改用户信息
    const updateUserInfoFn = async (data: AnyObject) => {
      const res = await updateUserInfo({
        ...data,
        StaffCode: user_id.value,
      });
      await staffFindInfo({ StaffCode: user_id.value });
      return res;
    };
    // 清理会员信息，退出登录时使用
    const exitLogin = () => {
      // 重新赋值为空对象,不破坏响应性
      Object.keys(profile).forEach((key) => {
        delete profile[key];
      });
      user_id.value = "";
      activePageStore.activePage = "home";
      // 清空所有本地存储数据
      uni.clearStorageSync();
      // 跳转到登录页面
      uni.reLaunch({
        url: "/pages/login/login",
      });
      console.log("退出登录成功", profile);
    };
    /************************导出 *************************** */
    // 记得 return
    return {
      profile, //用户信息
      login, //登录
      token, //token
      baseIP, //基准IP
      exitLogin, //退出登录
      user_id, //用户id
      staffFindInfo, //获取用户信息
      MenuString, //菜单列表
      warehouseList, //仓库列表
      defaultStash, //默认展示仓库
      changeStash, //切换仓库
      GodownCode, // 仓库编码
      updatePasswordFn, // 修改密码
      updateUserInfoFn, // 修改用户信息
      getStashlist,
    };
  },
  // TODO: 持久化
  {
    // 配置持久化
    persist: {
      // 调整为兼容多端的API
      storage: {
        setItem(key, value) {
          uni.setStorageSync(key, value);
        },
        getItem(key) {
          return uni.getStorageSync(key);
        },
      },
      paths: [
        "profile",
        "token",
        "baseIP",
        "user_id",
        "MenuString",
        "warehouseList",
        "defaultStash",
        "GodownCode",
      ],
    },
  }
);
